import { ref, watch } from 'vue';
import { message } from 'ant-design-vue';
import { fileUpload } from '#/api';

export interface UploadFileInfo {
  uid: string;
  name: string;
  status: string;
  url: string;
}

export function useImageUpload(
  modelValue: any, // 双向绑定的值
  onChange?: (value: string) => void, // 值改变的回调
  options = {
    maxCount: 8,
    field: 'filed', // 上传字段名
  },
) {
  const fileList = ref<UploadFileInfo[]>([]);
  const previewVisible = ref(false);
  const previewImage = ref('');
  const previewTitle = ref('');

  // 转换图片URL为文件列表格式
  const transformImageUrls = (urls: string[]) => {
    return urls.map((url, index) => ({
      uid: String(index),
      name: url.substring(url.lastIndexOf('/') + 1),
      status: 'done',
      url: url,
    }));
  };

  // 获取base64
  const getBase64 = (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result as string);
      reader.onerror = (error) => reject(error);
    });
  };

  // 处理预览
  const handlePreview = async (file: any) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    previewImage.value = file.url || file.preview;
    previewVisible.value = true;
    previewTitle.value =
      file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
  };

  // 处理上传
  const customUpload = async (options: any) => {
    const { file, onSuccess, onError } = options;
    try {
      const formData = new FormData();
      formData.append(options.field, file);

      const uploadRes = await fileUpload(formData);
      if (uploadRes?.url) {
        const newFile = {
          uid: Date.now().toString(),
          name: file.name,
          status: 'done',
          url: uploadRes.url,
        };
        onSuccess(uploadRes, newFile);

        // 更新值
        let currentUrls = [];
        try {
          currentUrls = modelValue.value ? JSON.parse(modelValue.value) : [];
        } catch (e) {
          currentUrls = [];
        }
        currentUrls.push(uploadRes.url);
        onChange?.(JSON.stringify(currentUrls));
      } else {
        onError('上传失败');
      }
    } catch (error) {
      onError('上传出错');
      message.error('上传失败');
    }
  };

  // 处理删除
  const handleRemove = (file: UploadFileInfo) => {
    try {
      const urls = modelValue.value ? JSON.parse(modelValue.value) : [];
      const index = urls.findIndex((url: string) => url === file.url);
      if (index > -1) {
        urls.splice(index, 1);
        onChange?.(JSON.stringify(urls));
      }
    } catch (e) {
      console.error('删除文件失败', e);
    }
    return true;
  };

  // 监听值变化
  watch(
    () => modelValue.value,
    (newVal) => {
      try {
        const urls = newVal ? JSON.parse(newVal) : [];
        fileList.value = transformImageUrls(urls);
      } catch (e) {
        fileList.value = [];
      }
    },
    { immediate: true },
  );

  return {
    fileList,
    previewVisible,
    previewImage,
    previewTitle,
    handlePreview,
    customUpload,
    handleRemove,
    closePreview: () => {
      previewVisible.value = false;
      previewTitle.value = '';
    },
  };
}
